package com.asktgapp.user.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.adapter.BrandAdapter;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.base.RentMachineBaseActivity;
import com.asktgapp.eventbus.RentMachineEvent;
import com.asktgapp.model.BrandVO;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.HomeServiceVO;
import com.asktgapp.model.ProvinceVO;
import com.asktgapp.model.RentInfoVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.HomeServiceDetailActivity;
import com.asktgapp.user.activity.PublishQiuzuActicity;
import com.asktgapp.user.activity.PublishRentActicity;
import com.asktgapp.user.activity.QiuZuDetailActivity;
import com.asktgapp.user.activity.RentDetailActivity;
import com.asktgapp.user.activity.UsedCheckActivity;
import com.asktgapp.utils.CustomPopWindow;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;
import com.asktgapp.widget.WordsNavigation;
import com.dd.plist.NSArray;
import com.dd.plist.NSDictionary;
import com.dd.plist.PropertyListParser;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 上门服务列表页
 */

public class HomeServiceFragment extends BaseFragment {

    @InjectView(R.id.recycle)
    RefreshRecyclerView mRefreshRecyclerView;
    @InjectView(R.id.rd_type)
    RadioButton mTypeButton;
    @InjectView(R.id.rd_brand)
    RadioButton mBrandButton;
    @InjectView(R.id.rd_city)
    RadioButton mCityButton;
    @InjectView(R.id.rd_select)
    RadioButton mSelectButton;
    @InjectView(R.id.tv_no_data)
    TextView noDataTV;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private int mPage = 1;
    private CustomPopWindow mListPopWindow = null;
    private CustomPopWindow mBrandPopWindow = null;
    private CustomPopWindow mCityPopWindow = null;
    private CustomPopWindow mSelectPopWindow = null;
    private RecyclerView mProviceRecyclerView, mCityRecyclerView;
    private BaseAdapter mProviceAdapter, mCityAdapter;
    //初始化地区数据集，所有省份的列表{省份编号，省份名称，List<该省份下的城市>}
    List<ProvinceVO> provinceData = new ArrayList<>();
    //0:出租,1求租
    private int type = 0;
    private String userid;
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();
    private String mChooseType = "";
    private String mChooseBrand = "";
    private int mChoosePro = 0;
    private int mChooseCity = 0;
    private List<BrandVO> list;
    private BaseAdapter mTypeAdapter;
    private String minTimeLimit = "";
    private String maxTimeLimit = "";
    private String tonnage = "";
    private String price = "";
    //    private Comparator comparator;
    //改进后的适配器，将数据的排序筛选匹配放在了新线程中执行，避免大量数据时的ANR错误
    private BrandAdapter mBAdapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_rent_machine, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {

        setHasOptionsMenu(true);
        getBaseActivity().setBackNavigationIcon();
        userid = PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID);
        mTypeButton.setVisibility(View.VISIBLE);
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getNetData(mPage);
            }
        });
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();

        mTypeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(true);
                mBrandButton.setChecked(false);
                mCityButton.setChecked(false);
                mSelectButton.setChecked(false);
                showPopListView();
                hideBrand();
                hideCity();
                hideSelect();

            }
        });
        mBrandButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(false);
                mBrandButton.setChecked(true);
                mCityButton.setChecked(false);
                mSelectButton.setChecked(false);
                hidePopListView();
                showBrand();
                hideCity();
                hideSelect();
            }
        });
        mCityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTypeButton.setChecked(false);
                mBrandButton.setChecked(false);
                mCityButton.setChecked(true);
                mSelectButton.setChecked(false);
                hidePopListView();
                hideBrand();
                showCity();
                hideSelect();
            }
        });
        mSelectButton.setVisibility(View.GONE);
//        mSelectButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mTypeButton.setChecked(false);
//                mBrandButton.setChecked(false);
//                mCityButton.setChecked(false);
//                mSelectButton.setChecked(true);
//                hidePopListView();
//                hideBrand();
//                hideCity();
//                showSelect();
//            }
//        });
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_home_service, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                if (data instanceof HomeServiceVO) {
                                    ImageView userHead = holder.getView(R.id.userHead);
                                    HomeServiceVO bean = (HomeServiceVO) data;
                                    if (mBaseAdapter.getItemIndex(bean) == 0)
                                        holder.getView(R.id.tvLine).setVisibility(View.VISIBLE);
                                    else
                                        holder.getView(R.id.tvLine).setVisibility(View.GONE);
                                    userHead.setVisibility(View.VISIBLE);
                                    holder.getView(R.id.userName).setVisibility(View.VISIBLE);
                                    holder.getView(R.id.serviceType).setVisibility(View.GONE);
                                    holder.setText(R.id.userName, bean.getUserName());
                                    holder.setText(R.id.serviceContent, bean.getServiceInfo());
                                    Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                    String timeStr = Utils.getAskTime(date);
                                    holder.setText(R.id.addTime, timeStr);
                                    String pro = bean.getProviceName().replaceAll("省", "");
                                    String city = bean.getCityName().replaceAll("市", "");
                                    if (TextUtils.isEmpty(pro + " " + city))
                                        holder.setText(R.id.serviceAddress, "未知地区");
                                    else
                                        holder.setText(R.id.serviceAddress, pro + " " + city);

                                    if (Util.isEmpty(bean.getHasCollection())) {
                                        holder.getView(R.id.serviceStatus).setVisibility(View.GONE);
                                    } else {
                                        holder.getView(R.id.serviceStatus).setVisibility(View.VISIBLE);
                                    }
//                                    ImageDisplayUtil.LoadNetImageWithUrl(userHead, getActivity(), bean.getUserPic());
                                    ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, bean.getUserPic());
                                    String type = bean.getServiceType();
                                    String serviceType = "维修";
                                    if (type.equals("1")) {
                                        serviceType = ("维修");
                                    } else if (type.equals("2")) {
                                        serviceType = ("检车");
                                    } else if (type.equals("3")) {
                                        serviceType = ("保养");
                                    } else if (type.equals("4")) {
                                        serviceType = ("评估");
                                    }
                                    holder.getView(R.id.serviceTypeTop).setVisibility(View.VISIBLE);
                                    holder.setText(R.id.serviceTypeTop, serviceType);

                                }
                            }

                            @Override
                            public void onItemClick(View view, int position) {
                                HomeServiceVO bean = (HomeServiceVO) mBaseAdapter.getData().get(position);
                                Intent intent = new Intent(getActivity(), HomeServiceDetailActivity.class);
                                intent.putExtra("id", String.valueOf(bean.getId()));
//                                intent.putExtra("unit", bean.getPrice_unit());
                                startActivity(intent);
                            }
                        });

                return holder;
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mBaseAdapter);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取省一级的数组
                    NSArray ary = (NSArray) PropertyListParser.parse(getActivity().getAssets().open("City.plist"));
                    for (int i = ary.count() - 1; i >= 0; i--) {
                        NSDictionary dic = (NSDictionary) ary.objectAtIndex(i);
                        ProvinceVO provinceVO = new ProvinceVO();
                        List<ProvinceVO.City> city = new ArrayList<>();
                        //循环遍历获取每个省的地区编号和名称
                        String areaid = dic.objectForKey("areaid").toJavaObject().toString();
                        String name = dic.objectForKey("areaname").toJavaObject().toString();
                        //从省一级的字典中获取该省下的城市字典，转换为数组
                        NSArray citys = (NSArray) dic.objectForKey("citys");
                        for (int j = citys.count() - 1; j >= 0; j--) {
                            //遍历数组获取每个城市的信息，由于文件中的默认顺序，为保证省会城市在前，采用倒序遍历
                            NSDictionary secDic = (NSDictionary) citys.objectAtIndex(j);
                            //获取城市的编号
                            String secAreaid = (secDic.objectForKey("areaid")).toJavaObject().toString();
                            //获取城市的名称
                            String secName = (secDic.objectForKey("areaname")).toJavaObject().toString();
                            ProvinceVO.City bean = new ProvinceVO.City();
                            bean.setAreaid(Integer.parseInt(secAreaid));
                            bean.setAreaname(secName);
                            //将新建的城市对象添加到该省份对象的城市列表中
                            city.add(bean);
                        }
                        ProvinceVO.City all = new ProvinceVO.City();
                        all.setAreaid(0);
                        all.setAreaname("全部");
                        city.add(0, all);
                        provinceVO.setAreaid(Integer.parseInt(areaid));
                        provinceVO.setAreaname(name);
                        provinceVO.setCitys(city);
                        provinceData.add(provinceVO);
                    }
                    ProvinceVO provinceVO = new ProvinceVO();
                    provinceVO.setAreaid(0);
                    provinceVO.setAreaname("全部");
                    List<ProvinceVO.City> city = new ArrayList<>();
                    ProvinceVO.City bean = new ProvinceVO.City();
                    bean.setAreaid(0);
                    bean.setAreaname("全部");
                    //将新建的城市对象添加到该省份对象的城市列表中
                    city.add(bean);
                    provinceVO.setCitys(city);
                    provinceData.add(0, provinceVO);


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //优化适配器
        {
            mBAdapter = new BrandAdapter(getActivity(), new BrandAdapter.ItemCallback() {
                @Override
                public void onItemClick(String string, String id) {
                    mChooseBrand = id;
                    if (Util.isEmpty(id))
                        mBrandButton.setText("品牌");
                    else
                        mBrandButton.setText(string);
                    hideBrand();
                    mPage = 1;
                    getNetData(1);

                }

                @Override
                public void onDataSetComplete() {
                    dismissProgress();
                }

                @Override
                public void onStartSetData() {
                    showProgress(getClass().getSimpleName());
                }
            });

        }
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.finish, menu);
        menu.getItem(0).setTitle("发布");
        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
            menu.getItem(0).setVisible(false);
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (checkIsLogin("登录后可体验更多内容")){

            startActivity(new Intent(getActivity(), UsedCheckActivity.class));

        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void loadData() {
        visibleLoading();
        getNetData(mPage);
        getType();
    }

    private void getType() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList.clear();
                    mTypeList = response.body().getResult();
                    DeviceTypeVO bean = new DeviceTypeVO();
                    bean.setId("0");
                    bean.setName("全部");
                    mTypeList.add(0, bean);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }


    private void getNetData(final int mPage) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", userid);
        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
            params.put("isEngineer", 1);
        } else {
            params.put("isEngineer", 0);
        }
        params.put("page", mPage);
        if (!Util.isEmpty(tonnage)) {
            params.put("tonnage", tonnage);
        }
        if ((!Util.isEmpty(mChooseType)) && (!mChooseType.equals("0"))) {
            if (!Util.isEmpty(mChooseBrand)) {
                params.put("brandId", mChooseBrand);
            } else {
                params.put("type", mChooseType);
            }
        }
        if (mChoosePro != 0) {
            params.put("province", mChoosePro);
            if (mChooseCity != 0) {
                params.put("city", mChooseCity);
            }
        }
        Call<ApiResponseBody<List<HomeServiceVO>>> call = apiservice.serviceList(params);
        call.enqueue(new Callback<ApiResponseBody<List<HomeServiceVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<HomeServiceVO>>> call, Response<ApiResponseBody<List<HomeServiceVO>>> response) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                mRefreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    List<HomeServiceVO> list = response.body().getResult();
                    if (mPage == 1) {

                        if (list.size() == 0) {
                            showNoData();
                        } else {
                            hideNoData();
                            mBaseAdapter.setData(list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    } else {
                        if (list.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<HomeServiceVO>>> call, Throwable t) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }

    public void showNoData() {
        noDataTV.setVisibility(View.VISIBLE);
        mRefreshRecyclerView.setVisibility(View.GONE);
    }

    public void hideNoData() {
        noDataTV.setVisibility(View.GONE);
        mRefreshRecyclerView.setVisibility(View.VISIBLE);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    private void hidePopListView() {
        if (mListPopWindow != null)
            mListPopWindow.dissmiss();
    }

    private void hideBrand() {
        if (mBrandPopWindow != null)
            mBrandPopWindow.dissmiss();
    }

    private void hideCity() {
        if (mCityPopWindow != null)
            mCityPopWindow.dissmiss();
    }

    private void hideSelect() {
        if (mSelectPopWindow != null)
            mSelectPopWindow.dissmiss();
    }

    private void showPopListView() {
        if (mListPopWindow != null) {
            mListPopWindow.showAsDropDown(mTypeButton, 0, 5);
        } else {
            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.item_recyclerview, null);
            FrameLayout bg = contentView.findViewById(R.id.bg);

            //处理popWindow 显示内容
            final RecyclerView recyclerView = contentView.findViewById(R.id.recycle);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            mTypeAdapter = new BaseAdapter(getActivity()) {
                @Override
                public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                    BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_type_choose, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            DeviceTypeVO bean = (DeviceTypeVO) data;
                            TextView type = holder.getView(R.id.tv_type);
                            ImageView choose = holder.getView(R.id.iv_choose);
                            type.setText(bean.getName());
                            if (bean.isChoose()) {
                                choose.setVisibility(View.VISIBLE);
                            } else {
                                choose.setVisibility(View.GONE);
                            }

                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            DeviceTypeVO bean = (DeviceTypeVO) mTypeAdapter.getData().get(position);
                            mChooseType = bean.getId();
                            List<DeviceTypeVO> list = mTypeAdapter.getData();
                            for (int i = 0; i < list.size(); i++) {
                                DeviceTypeVO vo = list.get(i);
                                if (vo.getId() == bean.getId()) {
                                    vo.setChoose(true);
                                } else {
                                    vo.setChoose(false);
                                }
                            }
                            mTypeAdapter.setData(list);
                            recyclerView.scrollToPosition(position);
                            mListPopWindow.dissmiss();
                            mPage = 1;
                            mChooseBrand = "";
                            if (bean.getName().equals("全部"))
                                mTypeButton.setText("类型");
                            else
                                mTypeButton.setText(bean.getName());
                            getNetData(mPage);
                        }
                    });
                    return holder;
                }
            };
            mTypeAdapter.setData(mTypeList);
            recyclerView.setAdapter(mTypeAdapter);
            //创建并显示popWindow
            mListPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mTypeButton.setChecked(false);

                        }
                    })
                    .setTouchable(true)
                    .setOutsideTouchable(true)
                    .create()
                    .showAsDropDown(mTypeButton, 0, 5);

            bg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListPopWindow.dissmiss();
                    mTypeButton.setChecked(false);
                }
            });
        }
    }

    private void showBrand() {
        getBrandLlist();
    }

    private void getBrandLlist() {


        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        if (Util.isEmpty(mChooseType) || mChooseType.equals("0")) {
            showTost("请先选择设备类型", 1);
            mBrandButton.setChecked(false);
            return;
        }
        params.put("typeId", mChooseType);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<List<BrandVO>>> call = apiservice.getBrandList(params);
        call.enqueue(new Callback<ApiResponseBody<List<BrandVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<BrandVO>>> call, Response<ApiResponseBody<List<BrandVO>>> response) {
                if (response.isSuccessful()) {
                    list = response.body().getResult();
                    BrandVO brandVO = new BrandVO();
                    brandVO.setName("全部");
                    brandVO.setIsHot(1);
                    brandVO.setTypeId(0);
                    brandVO.setId("");
                    list.add(0, brandVO);
                    initData();
                } else {
                    dismissProgress();
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<BrandVO>>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);

            }
        });

    }

    /****************************************** 展示品牌选择模块开始***********************/

    private void initData() {
        if (mBrandPopWindow != null) {
            mBrandPopWindow.showAsDropDown(mBrandButton, 0, 5);
            mBAdapter.setData(list);
            return;
        }
//        //对集合排序
//        Collections.sort(list, new Comparator<BrandVO>() {
//            @Override
//            public int compare(BrandVO lhs, BrandVO rhs) {
//                //根据拼音进行排序
//                return lhs.getPinyin().compareTo(rhs.getPinyin());
//            }
//        });
        final ListView mBrandListView;
//        final MyBrandAdapter mBrandAdapter;
        final WordsNavigation mBrandWordNavigation;

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_choose_brand, null);
        mBrandListView = contentView.findViewById(R.id.list);
        mBrandWordNavigation = contentView.findViewById(R.id.words);
//        mBrandAdapter = new MyBrandAdapter(getActivity(), list, new MyBrandAdapter.ItemCallback() {
//            @Override
//            public void onItemClick(String string, String id) {
//                mChooseBrand = id;
////                showTost(string, 0);
//                hideBrand();
//                mPage = 1;
//                getNetData(1);
//
//            }
//        });
        mBrandWordNavigation.setOnWordsChangeListener(new WordsNavigation.onWordsChangeListener() {
            @Override
            public void wordsChange(String words) {
                if (words.equals("#")) {
                    words = "热门品牌";
                }
//                for (int i = 0; i < mBrandAdapter.getData().size(); i++) {
//                    if (mBrandAdapter.getData().get(i).getHeadChar().equals(words)) {
//                        mBrandListView.setSelection(i);
//                        return;
//                    }
//                    String headerWord = mBrandAdapter.getData().get(i).getHeadChar().toUpperCase();
//                    //将手指按下的字母与列表中相同字母开头的项找出来
//                    if (words.equals(headerWord)) {
//                        //将列表选中哪一个
//                        mBrandListView.setSelection(i);
//                        //找到开头的一个即可
//                        return;
//                    }
//                }
                for (int i = 0; i < mBAdapter.getData().size(); i++) {
                    if (mBAdapter.getData().get(i).getHeadChar().equals(words)) {
                        mBrandListView.setSelection(i);
                        return;
                    }
                    String headerWord = mBAdapter.getData().get(i).getHeadChar().toUpperCase();
                    //将手指按下的字母与列表中相同字母开头的项找出来
                    if (words.equals(headerWord)) {
                        //将列表选中哪一个
                        mBrandListView.setSelection(i);
                        //找到开头的一个即可
                        return;
                    }
                }
            }
        });


//        mBrandListView.setAdapter(mBrandAdapter);
        mBrandListView.setAdapter(mBAdapter);

        mBrandListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                //当滑动列表的时候，更新右侧字母列表的选中状态
//                if (mBrandAdapter.getData().get(firstVisibleItem).getHeadChar().equals("热门品牌")) {
//                    mBrandWordNavigation.setTouchIndex("#");
//                } else {
//                    mBrandWordNavigation.setTouchIndex(mBrandAdapter.getData().get(firstVisibleItem).getHeadChar().toUpperCase());
//                }
                //当滑动列表的时候，更新右侧字母列表的选中状态
                if (mBAdapter.getData().size() > 0) {
                    if (mBAdapter.getData().get(firstVisibleItem).getHeadChar().equals("热门品牌")) {
                        mBrandWordNavigation.setTouchIndex("#");
                    } else {
                        mBrandWordNavigation.setTouchIndex(mBAdapter.getData().get(firstVisibleItem).getHeadChar().toUpperCase());
                    }
                }
            }
        });
        //创建并显示popWindow
        mBrandPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        mBrandButton.setChecked(false);
//
                    }
                })
                .setTouchable(true)
                .setOutsideTouchable(true)
                .create()
                .showAsDropDown(mBrandButton, 0, 5);
        mBAdapter.setData(list);
//        dismissProgress();

    }

    int mChoosePositon = 0;

    /****************************************** 展示城市选择模块开始***********************/
    private String cityText = "全部";

    private void showCity() {
        mChoosePositon = 0;
        if (mCityPopWindow != null) {
            mCityPopWindow.showAsDropDown(mCityButton, 0, 5);
            mCityAdapter.setData(provinceData.get(mChoosePositon).getCitys());
        } else {
            //显示地区POp

            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_choose_city, null);
            mProviceRecyclerView = contentView.findViewById(R.id.left_recycler);
            mCityRecyclerView = contentView.findViewById(R.id.right_recycler);
            mProviceAdapter = new BaseAdapter(getActivity()) {
                @Override
                public BaseViewHolder getViewHolder(ViewGroup parent, final int viewType) {
                    BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_province, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            if (data instanceof ProvinceVO) {
                                TextView province = holder.getView(R.id.textView);
                                ProvinceVO provinceVO = (ProvinceVO) data;
                                province.setText(provinceVO.getAreaname());
                                if (viewType == 1) {
                                    province.setBackgroundColor(Color.WHITE);
                                } else {
                                    province.setBackgroundColor(Color.parseColor("#e0e0e0"));
                                }
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            mChoosePositon = position;
                            mProviceAdapter.notifyDataSetChanged();
                            mProviceRecyclerView.smoothScrollToPosition(mChoosePositon);
                            ProvinceVO provinceVO = (ProvinceVO) mProviceAdapter.getData().get(position);
                            mCityAdapter.setData(provinceVO.getCitys());
                            mCityRecyclerView.smoothScrollToPosition(0);
                            mChoosePro = provinceVO.getAreaid();
                            cityText = provinceVO.getAreaname();
                        }
                    });
                    return holder;
                }

                @Override
                public int getItemViewType(int position) {
                    if (position == mChoosePositon) {
                        return 1;
                    } else return 0;
                }
            };
            mCityAdapter = new BaseAdapter(getActivity()) {
                @Override
                public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                    BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_city, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            if (data instanceof ProvinceVO.City) {
                                TextView city = holder.getView(R.id.city);
                                ProvinceVO.City bean = (ProvinceVO.City) data;
                                city.setText(bean.getAreaname());
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            ProvinceVO.City city = (ProvinceVO.City) mCityAdapter.getData().get(position);
//                            showTost("名称：" + city.getAreaname() + "  编号：" + city.getAreaid(), 1);
                            if (city.getAreaid() == 110100) {
                                mChoosePro = 110000;
                            }
                            if (mChoosePositon == 0) {
                                mChoosePro = 0;
//                                if (city.getAreaid() == 0) {
//                                    mChoosePro = 110000;
//                                }
                            }
                            mChooseCity = city.getAreaid();
                            mPage = 1;
                            hideCity();
                            if (cityText.equals("全部")) {
                                mCityButton.setText("地区");
                            } else {
                                if (!city.getAreaname().equals("全部")) {
                                    mCityButton.setText(city.getAreaname());
                                } else {
                                    mCityButton.setText(cityText);
                                }
                            }
                            cityText = "全部";
                            getNetData(mPage);
                        }
                    });
                    return holder;
                }
            };
            mCityRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            mProviceRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            mCityRecyclerView.setAdapter(mCityAdapter);
            mProviceRecyclerView.setAdapter(mProviceAdapter);
            mProviceAdapter.setData(provinceData);
            mCityAdapter.setData(provinceData.get(0).getCitys());

            //创建并显示popWindow
            mCityPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mCityButton.setChecked(false);
                        }
                    })
                    .setTouchable(true)
                    .setOutsideTouchable(true)
                    .create()
                    .showAsDropDown(mCityButton, 0, 5);
        }
    }

//    CheckBox[] Weight = new CheckBox[5];
//    CheckBox[] Price = new CheckBox[5];
//    private LinearLayout mGongQIll, mPricell;
//    private TextView mMIN, mMAX;
//    private LinearLayout mContainer;
//
//    public String getWeight() {
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < Weight.length; i++) {
//            if (Weight[i].isChecked()) {
//                sb.append(i + ",");
//            }
//        }
//        if (Util.isEmpty(sb.toString())) {
//            return "";
//        } else
//            return sb.toString().substring(0, sb.toString().length() - 1);
//    }
//
//    public String getPrice() {
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < Price.length; i++) {
//            if (Price[i].isChecked()) {
//                sb.append(i + ",");
//            }
//        }
//        if (Util.isEmpty(sb.toString())) {
//            return "";
//        } else
//            return sb.toString().substring(0, sb.toString().length() - 1);
//    }
//
//
//    public void showSelect() {
//        if (mSelectPopWindow != null) {
//            if (type == 0) {
//                mGongQIll.setVisibility(View.GONE);
//                mPricell.setVisibility(View.VISIBLE);
//            } else {
//                mGongQIll.setVisibility(View.VISIBLE);
//                mPricell.setVisibility(View.GONE);
//            }
//            mSelectPopWindow.showAsDropDown(mCityButton, 0, 5);
//        } else {
//            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.item_select_rent, null);
//            mMIN = contentView.findViewById(R.id.et_min);
//            mMAX = contentView.findViewById(R.id.et_max);
//            mContainer = contentView.findViewById(R.id.ll_container);
//            mContainer.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    //不做处理，用来避免点击内部无点击事件的区域时，会出发背景的点击事件（导致弹窗消失）
//                }
//            });
//            FrameLayout bg = contentView.findViewById(R.id.bg);
//            Price[0] = contentView.findViewById(R.id.cb_price1);
//            Price[1] = contentView.findViewById(R.id.cb_price2);
//            Price[2] = contentView.findViewById(R.id.cb_price3);
//            Price[3] = contentView.findViewById(R.id.cb_price4);
//            Price[4] = contentView.findViewById(R.id.cb_price5);
//            Weight[0] = contentView.findViewById(R.id.cb_weight1);
//            Weight[1] = contentView.findViewById(R.id.cb_weight2);
//            Weight[2] = contentView.findViewById(R.id.cb_weight3);
//            Weight[3] = contentView.findViewById(R.id.cb_weight4);
//            Weight[4] = contentView.findViewById(R.id.cb_weight5);
//            mGongQIll = contentView.findViewById(R.id.ll_gongqi);
//            mPricell = contentView.findViewById(R.id.ll_price);
//            TextView sure = contentView.findViewById(R.id.tv_sure);
//            if (type == 0) {
//                mGongQIll.setVisibility(View.GONE);
//                mPricell.setVisibility(View.VISIBLE);
//            } else {
//                mGongQIll.setVisibility(View.VISIBLE);
//                mPricell.setVisibility(View.GONE);
//            }
//            mSelectPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
//                    .setView(contentView)
//                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
//                    .setOnDissmissListener(new PopupWindow.OnDismissListener() {
//                        @Override
//                        public void onDismiss() {
//                            mSelectButton.setChecked(false);
//                        }
//                    })
//                    .setTouchable(true)
//                    .setOutsideTouchable(true)
//                    .create()
//                    .showAsDropDown(mCityButton, 0, 5);
//
//
//            sure.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    minTimeLimit = mMIN.getText().toString();
//                    maxTimeLimit = mMAX.getText().toString();
//                    tonnage = getWeight();
//                    price = getPrice();
//                    hideSelect();
//                    mSelectButton.setChecked(false);
//                    mPage = 1;
//                    getNetData(mPage);
//
//                }
//            });
//
//            TextView reset = contentView.findViewById(R.id.tv_reset);
//            reset.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    doRest();
//                }
//            });
//
//            bg.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    mSelectPopWindow.dissmiss();
//                    mSelectButton.setChecked(false);
//
//                }
//            });
//
//
//        }
//
//    }
//
//    private void doRest() {
//        mMIN.setText("");
//        mMAX.setText("");
//
//        if (Weight != null) {
//            for (int i = 0; i < Weight.length; i++) {
//                Weight[i].setChecked(false);
//            }
//        }
//        if (Price != null) {
//            for (int i = 0; i < Price.length; i++) {
//                Price[i].setChecked(false);
//            }
//        }
//    }
}
